<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-10
 * Time: 15:41:05
 * Info:
 */

namespace plugin\huiblog\app\controller;

use support\Request;
use think\facade\Db;
use support\lib\GetImgSrc;
use plugin\huiblog\app\model\Keywords as KeywordsModel;
use plugin\huiblog\app\model\ArticleCate as ArticleCateModel;
use plugin\huiblog\app\common\CacheClear;

class BlogController
{

    const ATTRIBUTE = [
        1 => '精华',
        2 => '热门',
        3 => '推荐',
    ];

    /**
     * 博文列表
     */
    public function index(Request $request)
    {
        $this->model      = Db::table('blog_article');
        $articleCateModel = new ArticleCateModel();
        $cates            = $articleCateModel->getPidMenuList();

        if ($request->isAjax()) {
            $limit      = (int)$request->input('limit', 15);
            $page       = (int)$request->input('page', 1);
            $key        = $request->input('key');
            $first      = ($page - 1) * $limit;
            $where      = function ($query) use ($key) {
                $query->where('delete_time', 0);
                if ( ! empty($key['id'])) {
                    $query->where('id', $key['id']);
                }
                if ( ! empty($key['article_cate_id'])) {
                    $query->where('article_cate_id', $key['article_cate_id']);
                }
                if ( ! empty($key['title'])) {
                    $query->whereLike('title', "%".$key['title']."%");
                }
                if (isset($key['type']) && $key['type'] != '') {
                    $query->where('type', $key['type']);
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
            };
            $count      = $this->model->where($where)->count();
            $data       = $this->model->where($where)->limit($first, $limit)->order('id desc')->select()->toArray();
            $cates      = $this->articleCates();
            $catesNames = array_column($cates, 'title', 'id');

            foreach ($data as $key => $v) {
                $data[$key]['cate_name']   = $catesNames[$v['article_cate_id']] ?? '';
                $data[$key]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
            }

            return json(['code' => 0, 'count' => $count, 'data' => $data, 'msg' => 'ok']);
        }

        return view('admin/blog/index', ['cates' => $cates, 'attributes' => self::ATTRIBUTE]);
    }

    /**
     * 博文添加
     */
    public function add(Request $request)
    {
        $this->model      = Db::table('blog_article');
        $keywordsModel    = new KeywordsModel();
        $articleCateModel = new ArticleCateModel();

        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['article_cate_id'])) {
                return json(['code' => 0, 'msg' => '请选择分类']);
            }
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '标题不能为空']);
            }
            if (isset($param['auto_image']) && $param['auto_image'] == 1 && $param['thumb'] == '') {
                $param['thumb'] = GetImgSrc::src($param['content']);
                $param['thumb'] = $param['thumb'] ?? "";
            }
            //截取描述
            $param['content']     = htmlspecialchars_decode($param['content']);
            $param['desc']        = empty($param['desc']) ? mb_substr(strip_tags($param['content']), 0, 260,
                'utf-8') : $param['desc'];
            $param['create_time'] = time();
            $param['update_time'] = time();
            try {
                $articleId = $this->model->strict(false)->insertGetId($param);
                //关联关键字
                if (isset($param['keyword_names']) && $param['keyword_names']) {
                    $keywordsModel->articleKeywordsEdit($articleId, $param['keyword_names']);
                }
                CacheClear::clearArticleCount();

                return json(['code' => 200, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        $cates = $articleCateModel->getPidMenuList();

        return view('admin/blog/add', ['cates' => $cates, 'attributes' => self::ATTRIBUTE]);
    }

    /**
     * 博文编辑
     */
    public function edit(Request $request)
    {
        $this->model      = Db::table('blog_article');
        $keywordsModel    = new KeywordsModel();
        $articleCateModel = new ArticleCateModel();
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['id'])) {
                return json(['code' => 0, 'msg' => '参数错误']);
            }
            if (empty($param['article_cate_id'])) {
                return json(['code' => 0, 'msg' => '请选择分类']);
            }
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '标题不能为空']);
            }
            if (isset($param['auto_image']) && $param['auto_image'] == 1 && $param['thumb'] == '') {
                $param['thumb'] = GetImgSrc::src($param['content']);
                $param['thumb'] = $param['thumb'] ?? "";
            }
            $param['content']     = htmlspecialchars_decode($param['content']);
            $param['update_time'] = time();
            //关联关键字
            if (isset($param['keyword_names']) && $param['keyword_names']) {
                $keywordsModel->articleKeywordsEdit($param['id'], $param['keyword_names']);
            }
            //截取描述
            $param['desc'] = empty($param['desc']) ? mb_substr(strip_tags($param['content']), 0, 260,
                'utf-8') : $param['desc'];
            try {
                $this->model->where('id', $param['id'])->data($param)->strict(false)->update();
                CacheClear::clearArticleCount();

                return json(['code' => 200, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        $id   = $request->get('id');
        $data = $this->model->find($id);
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '获取数据失败']);
        }
        $keyword_array = Db::table('blog_article_keywords')->alias('i')->leftJoin(['blog_keywords' => 'k'],
            'k.id = i.keywords_id')->where([
            'i.aid'         => $id,
            'k.status'      => 1,
            'k.delete_time' => 0
        ])->order('i.create_time asc,i.keywords_id desc')->select()->toArray();

        $data['keyword_ids']   = implode(",", array_column($keyword_array, 'keywords_id'));
        $data['keyword_names'] = implode(',', array_column($keyword_array, 'title'));
        $data['keyword_array'] = $keyword_array;

        $cates = $articleCateModel->getPidMenuList();

        return view('admin/blog/edit', ['data' => $data, 'cates' => $cates, 'attributes' => self::ATTRIBUTE]);
    }

    public function delete(Request $request)
    {
        $this->model = Db::table('blog_article');
        $id          = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $this->model->where('id', $id)->useSoftDelete('delete_time', time())->delete();
        CacheClear::clearArticleCount();

        return json(['code' => 200, 'msg' => '删除成功']);
    }

    private function articleCates()
    {
        $list = Db::table('blog_article_cate')->field('id,pid,sort,title')->select()->toArray();

        return $list;
    }

}
